package com.yanqu.road.server.cmd;

import com.yanqu.road.connect.AgentServerLinkControl;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.union.UnionActivityGroupProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.manger.CrossActivityProcessMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Cmd(code = Protocol.A_UNION_ACTIVITY_GROUP_SYNC, desc = "同步分组数据")
public class AgentUnionActivityGroupSyncCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage yanQuMessage) throws Exception {

        long serverId = ConfigHelper.getLong("serverId");

        // agentServer保存数据
        UnionActivityGroupProto.UnionActivityGroupSyncReqMsg syncMsg = UnionActivityGroupProto.UnionActivityGroupSyncReqMsg.parseFrom(yanQuMessage.getBytes());
        Map<Integer, Map<Integer, Integer>> mapMap = new ConcurrentHashMap<>();
        for (UnionActivityGroupProto.UnionActivityGroupMsg groupMsg : syncMsg.getAllGroupList()) {
            if (!groupMsg.getServerIdList().contains(serverId)) {
                continue; // 去掉不需要的数据
            }
            mapMap.putIfAbsent(groupMsg.getActivityId(), new ConcurrentHashMap<>());
            mapMap.get(groupMsg.getActivityId()).put(groupMsg.getGroupId(), groupMsg.getCrossServerId());
        }
        for (Map.Entry<Integer, Map<Integer, Integer>> entry : mapMap.entrySet()) {
            CrossActivityProcessMgr.putUnionActivityProcessMap(entry.getKey(), entry.getValue());
        }

        // 转发到自己游戏服
        YanQuMessage message = YanQuMessageUtils.buildMessageByte(Protocol.S_UNION_ACTIVITY_GROUP_SYNC, yanQuMessage.getBytes());
        AgentServerLinkControl.routeGame(message);
    }
}
